package net.thick4.context.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * Springの提供する{@link org.springframework.web.filter.RequestContextFilter}
 * と同等の働きをするServletFilterの実装。
 * 
 * ただし、内部で{@link RequestContextHolder#setRequestAttributes(RequestAttributes)}
 * に設定している{@link RequestAttributes}実装クラスを{@link ServletRequestAttributes}から{@link ServletWebRequest}
 * に変更している点とthreadContextInheritable属性を持たない点が異なる。
 * 
 * @see org.springframework.web.context.request.RequestContextHolder
 * @see org.springframework.web.filter.RequestContextFilter
 */
public class RequestContextFilter extends OncePerRequestFilter {

	protected void doFilterInternal(
			HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		ServletWebRequest attributes = new ServletWebRequest(request, response);
		LocaleContextHolder.setLocale(request.getLocale());
		RequestContextHolder.setRequestAttributes(attributes);
		if (logger.isDebugEnabled()) {
			logger.debug("Bound request context to thread: " + request);
		}
		try {
			filterChain.doFilter(request, response);
		}
		finally {
			RequestContextHolder.resetRequestAttributes();
			LocaleContextHolder.resetLocaleContext();
			attributes.requestCompleted();
			if (logger.isDebugEnabled()) {
				logger.debug("Cleared thread-bound request context: " + request);
			}
		}
	}
}
